//
//  MyViewController.m
//  Travel assistant
//
//  Created by 王京 on 16/3/7.
//  Copyright © 2016年 旅游助手. All rights reserved.
//

#import "MyViewController.h"
#import "PointViewController.h"
#import <Masonry.h>
#import "MyCollectionViewCell.h"
#import "CreateTableViewController.h"
#import "LoginViewController.h"
#import "RegistViewController.h"
#import "DataHelper.h"
#import "SetViewController.h"
#import "UserOfMine.h"
#import "UserInfo.h"
#import <AVOSCloud/AVOSCloud.h>
#import <UIImageView+WebCache.h>


@interface MyViewController ()<UIScrollViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic,strong) UIImagePickerController *pickImage;
@property (nonatomic,strong) UserInfo *mine;
@property (strong, nonatomic) UIImage *avatarImage;
@end

@implementation MyViewController




- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"会员中心";
    
    //scrollView不能写在mySet方法中，下滑手势调用的时候会重新创建。会有问题。
    self.scrollView = [[UIScrollView alloc]init];
    
    [self.view addSubview:self.scrollView];
    [self mySet];
    //        self.scrollView.backgroundColor = [UIColor blueColor];
    
    self.segment.selectedSegmentIndex = 0;
    
    [self.pointBtn addTarget:self action:@selector(pointBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    //登陆
    [self.loginBtn addTarget:self action:@selector(loginBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    //注册
    [self.registBtn addTarget:self action:@selector(registBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    //上划手势
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeAction)];
    
    [swipe setDirection:(UISwipeGestureRecognizerDirectionUp)];
    
    [self.view addGestureRecognizer:swipe];
    
    //下划手势
    UISwipeGestureRecognizer *swipe1 = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipe1Action)];
    
    [swipe1 setDirection:(UISwipeGestureRecognizerDirectionDown)];
    
    [self.view addGestureRecognizer:swipe1];
    
    
    UIBarButtonItem *rig = [[UIBarButtonItem alloc]initWithTitle:@"设置" style:(UIBarButtonItemStylePlain) target:self action:@selector(setAction)];
    
    self.navigationItem.rightBarButtonItem = rig;
    
    
    
    
    if (HELP.loginToView == YES) {
        
        [self.titleLabel removeFromSuperview];
        [self.loginBtn removeFromSuperview];
        [self.registBtn removeFromSuperview];
        
        
        self.loginImageV = [[UIImageView alloc]init];
        
        self.loginImageV.frame = CGRectMake(self.view.frame.size.width*0.5-40, 10, 80, 80);
        
        [self.loginImageV sd_setImageWithURL:[NSURL URLWithString:HELP.iconURL]];
        
        [self.headView addSubview:self.loginImageV];
        self.loginImageV.image = HELP.placeHoderImageV.image;
        //换头像手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
        
        [self.loginImageV addGestureRecognizer:tap];
        
        self.loginImageV.userInteractionEnabled = YES;
        
        self.loginNameLabel = [[UILabel alloc]init];
        
        self.loginNameLabel.frame = CGRectMake(CGRectGetMinX(self.loginImageV.frame), CGRectGetMaxY(self.loginImageV.frame) , 100, 40);
        
        self.loginNameLabel.text = HELP.userName;
        
        self.loginNameLabel.textAlignment = NSTextAlignmentCenter;
        
        [self.headView addSubview:self.loginNameLabel];
        
        [self.navigationItem setHidesBackButton:YES];
        
    }
    
    if (HELP.registToView == YES) {
        [self.titleLabel removeFromSuperview];
        [self.loginBtn removeFromSuperview];
        [self.registBtn removeFromSuperview];
        
        self.loginImageV = [[UIImageView alloc]init];
        
        self.loginImageV.frame = CGRectMake(self.view.frame.size.width*0.5-40, 10, 80, 80);
        
        self.loginImageV.userInteractionEnabled = YES;
        
        [self.headView addSubview:self.loginImageV];
        //换头像手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
        
        [self.loginImageV addGestureRecognizer:tap];
        
        self.loginImageV.image = HELP.placeHoderImageV.image;
        
        self.loginNameLabel = [[UILabel alloc]init];
        
        self.loginNameLabel.frame = CGRectMake(CGRectGetMinX(self.loginImageV.frame), CGRectGetMaxY(self.loginImageV.frame) , 100, 40);
        
        self.loginNameLabel.text = HELP.userName;
        
        [self.headView addSubview:self.loginNameLabel];
        
        [self.navigationItem setHidesBackButton:YES];

        
        
    }
    
    
    
    
    
    
    [self.navigationItem setHidesBackButton:YES];
    
    
//    /**
//     *  存储头像
////     */
//    AVQuery *query = [AVQuery queryWithClassName:@"headImage"];
//    [query whereKey:@"username" equalTo:[AVUser currentUser].username];
//    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
//        if (objects.count > 0) {
//            AVObject * obj = [objects lastObject];
//            AVFile * imageFile = [obj valueForKey:@"headimage"];
//            [self.loginImageV sd_setImageWithURL:[NSURL URLWithString:imageFile.url]];
//        }
//    }];
    
    
    // Do any additional setup after loading the view.
}


- (void)saveImg{
    
    // 查询是否已有改用户
    AVQuery *query = [AVQuery queryWithClassName:@"headImage"];
    [query whereKey:@"username" equalTo:[AVUser currentUser].username];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (objects.count > 0) {
            // 找到了该用户
            NSData *imageData = UIImagePNGRepresentation(self.loginImageV.image);
            AVFile *imageFile = [AVFile fileWithName:@"image.png" data:imageData];
            [imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                
            } progressBlock:^(NSInteger percentDone) {
                NSLog(@"%lu",(long)percentDone);
            }];
            
            AVObject *userPost = [objects lastObject];
            [userPost setObject:[AVUser currentUser].username forKey:@"username"];
            [userPost setObject:imageFile            forKey:@"headerimage"];
            [userPost saveInBackground];
        } else if(!error) {
            // 输出错误信息
            NSData *imageData = UIImagePNGRepresentation(self.loginImageV.image);
            AVFile *imageFile = [AVFile fileWithName:@"image.png" data:imageData];
            [imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                
            } progressBlock:^(NSInteger percentDone) {
                NSLog(@"%lu",(long)percentDone);
            }];
            
            AVObject *userPost = [AVObject objectWithClassName:@"headerImage"];
            [userPost setObject:[AVUser currentUser].username forKey:@"username"];
            [userPost setObject:imageFile            forKey:@"headerimage"];
            [userPost saveInBackground];
        }else
        {
            NSLog(@"发生了错误");
        }
    }];
    
    
    
    
    
    
}

- (void)mySet{
    
    
    //设置scrollView
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(self.view);
        
    }];
    //上方的视图
    self.headView = [[UIView alloc]init];
    
    //    self.headView.backgroundColor = [UIColor redColor];
    
    [self.scrollView addSubview:self.headView];
    
    [self.headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.scrollView.mas_bottom);
        
        make.left.equalTo(self.scrollView);
        
        make.right.equalTo(self.scrollView);
        
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width, self.view.frame.size.height*0.2));
        
    }];
    
    //设置segment
    NSArray *array = @[@"旅行日记",@"行程账单",@"数据同步"];
    
    self.segment = [[UISegmentedControl alloc]initWithItems:array];
    
    self.segment.backgroundColor = [UIColor whiteColor];
    
    self.segment.tintColor = [UIColor blackColor];
    
    [self.scrollView addSubview:self.segment];
    
    [self.segment mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headView.mas_bottom);
        
        make.left.equalTo(self.scrollView);
        
        make.right.equalTo(self.scrollView);
        
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width, self.view.frame.size.height*0.05));
        
    }];
    
    [self.segment addTarget:self action:@selector(segMentAction:) forControlEvents:(UIControlEventValueChanged)];
    
    //设置segment下方的视图
    self.HomeView = [[UIView alloc]init];
    
    //    self.HomeView.backgroundColor = [UIColor blackColor];
    
    [self.scrollView addSubview:self.HomeView];
    
    [self.HomeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.segment.mas_bottom);
        
        make.left.equalTo(self.scrollView);
        
        make.right.equalTo(self.scrollView);
        
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width, self.view.frame.size.height-self.segment.frame.size.height));
        
    }];
    
    self.HomeView.userInteractionEnabled = YES;
    
    //设置segment上方视图的 title ，登陆和注册
    self.titleLabel = [[UILabel alloc]init];
    
    self.titleLabel.frame = CGRectMake(self.view.frame.size.width*0.3, 20, 200, 30);
    
    self.titleLabel.backgroundColor = [UIColor whiteColor];
    
    self.loginBtn = [UIButton buttonWithType:(UIButtonTypeSystem)];
    
    self.loginBtn.frame = CGRectMake(CGRectGetMinX(self.titleLabel.frame)+30, 70, 30, 30);
    
    [self.loginBtn setTitle:@"登陆" forState:(UIControlStateNormal)];
    
    self.registBtn = [UIButton buttonWithType:(UIButtonTypeSystem)];
    
    self.registBtn.frame = CGRectMake(CGRectGetMinX(self.loginBtn.frame)+60, 70, 30, 30);
    
    [self.registBtn setTitle:@"注册" forState:(UIControlStateNormal)];
    
    self.titleLabel.text = @"欢迎使用[旅游助手]";
    
    //    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    self.titleLabel.font = [UIFont systemFontOfSize:16];
    
    [self.headView addSubview:self.titleLabel];
    
    [self.headView addSubview:self.loginBtn];
    
    [self.headView addSubview:self.registBtn];
    
    self.imageV = [[UIImageView alloc]init];
    
    self.imageV.frame = CGRectMake(90,20 , self.view.frame.size.width*0.5, self.view.frame.size.height*0.4);
    
    self.imageV.image = [UIImage imageNamed:@"9.jpg"];
    
    self.imageV.userInteractionEnabled = YES;
    
    self.imageV.backgroundColor = [UIColor redColor];
    
    [self.HomeView addSubview:self.imageV];
    
    
    self.homeLabel = [[UILabel alloc]init];
    
    self.homeLabel.frame = CGRectMake(90, CGRectGetMaxY(self.imageV.frame), self.view.frame.size.width, 30);
    
    self.homeLabel.backgroundColor = [UIColor whiteColor];
    
    self.homeLabel.text = @"你还没有撰写任何旅行日记";
    
    [self.HomeView addSubview:self.homeLabel];
    
    
    self.pointBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    
    self.pointBtn.frame = CGRectMake(90, CGRectGetMaxY(self.homeLabel.frame), self.view.frame.size.width*0.5, 40);
    
    [self.pointBtn setTitle:@"查看如何写日记→" forState:(UIControlStateNormal)];
    
    //    self.pointBtn.backgroundColor = [UIColor grayColor];
    
    [self.HomeView addSubview:self.pointBtn];
    
    
    
}
//上划手势
-(void)swipeAction{
    
    [self.headView removeFromSuperview];
    
    //更改segment位置
    [self.segment mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.scrollView.mas_bottom);
        
        make.left.equalTo(self.scrollView);
        
        make.right.equalTo(self.scrollView);
        
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width, self.view.frame.size.height*0.05));
        
    }];
    
    
}
//下滑手势
-(void)swipe1Action{
    
    [self.scrollView addSubview:self.headView];
    //移除过headView,所以重新添加
    [self.headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.scrollView.mas_bottom);
        
        make.left.equalTo(self.scrollView);
        
        make.right.equalTo(self.scrollView);
        
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width, self.view.frame.size.height*0.2));
        
    }];
    //更改segment的位置
    [self.segment mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headView.mas_bottom);
        
        make.left.equalTo(self.scrollView);
        
        make.right.equalTo(self.scrollView);
        
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width, self.view.frame.size.height*0.05));
        
    }];
    
    
}


//segment方法
- (void)segMentAction:(UISegmentedControl *)segment{
    if (self.segment.selectedSegmentIndex == 0) {
        [self.HomeView addSubview:self.imageV];
        [self.HomeView addSubview:self.homeLabel];
        [self.HomeView addSubview:self.pointBtn];
        
        [self.collectionView removeFromSuperview];
        
        
    }else if(self.segment.selectedSegmentIndex == 1){
        [self.imageV removeFromSuperview];
        [self.homeLabel removeFromSuperview];
        [self.pointBtn removeFromSuperview];
        
        [self addCollection];
        
    }else if(self.segment.selectedSegmentIndex == 2){
        
        [self.collectionView removeFromSuperview];
        
    }
    
}
//懒加载  存储数量数组
- (NSMutableArray *)countArray{
    if (_countArray == nil) {
        _countArray = [NSMutableArray array];
    }
    return _countArray;
}


//第二个segment
- (void)addCollection{
    self.layout = [[UICollectionViewFlowLayout alloc]init];
    
    self.layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 40);
    
    self.layout.itemSize = CGSizeMake(self.HomeView.frame.size.width*0.4, self.HomeView.frame.size.height*0.2);
    
    self.layout.minimumLineSpacing = 20;
    
    self.layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.HomeView.frame.size.width, self.HomeView.frame.size.height) collectionViewLayout:self.layout];
    
    
    self.collectionView.delegate = self;
    
    self.collectionView.dataSource = self;
    
    self.collectionView.bounces = NO;
    
    self.collectionView.showsVerticalScrollIndicator = NO;
    
    self.collectionView.userInteractionEnabled = YES;
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    [self.HomeView addSubview:self.collectionView];
    
    [self.collectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"Cell"];
}


//collectionView方法

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    if (indexPath.row == 0) {
        
        cell.imageV.image = [UIImage imageNamed:@"白纸.jpg"];
        
        [cell.btn setBackgroundImage:[UIImage imageNamed:@"加号"] forState:(UIControlStateNormal)];
        
        
    }
    return cell;
    
    
}



- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        
        CreateTableViewController *create = [[CreateTableViewController alloc]init];
        
        [self.navigationController pushViewController:create animated:YES];
    }
    
    
}

//第一个segment界面的点击事件
- (void)pointBtnAction{
    PointViewController *p = [[PointViewController alloc]init];
    
    [self.navigationController pushViewController:p animated:YES];
    
}



//登陆跳转
- (void)loginBtnAction{
    
    LoginViewController *login = [[LoginViewController alloc]init];
    
    [self.navigationController pushViewController:login animated:YES];
    
}

- (void)registBtnAction{
    
    RegistViewController *regist = [[RegistViewController alloc]init];
    
    [self.navigationController pushViewController:regist animated:YES];
}


- (void)setAction{
    
    SetViewController *set = [[SetViewController alloc]init];
    
    [self.navigationController pushViewController:set animated:YES];
    
    
}


- (void)tapAction{
//    BigAvatarViewController *bigAvatarVC = [[BigAvatarViewController alloc] initWithNibName:@"BigAvatarViewController" bundle:nil];
//    bigAvatarVC.avatarImage              = self.avatarImage;
//    [self.navigationController pushViewController:bigAvatarVC animated:YES];
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"设置背景图片" message:nil  preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }];
    
    UIAlertAction * photo = [UIAlertAction actionWithTitle:@"相册" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController * imgController = [[UIImagePickerController alloc] init];
        imgController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //        imgController.allowsEditing = YES;
        imgController.delegate = self;
        [self presentViewController:imgController animated:YES completion:nil
         ];
    }];
    UIAlertAction * camera = [UIAlertAction actionWithTitle:@"拍照" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeCamera)]) {
            UIImagePickerController * cameraController = [[UIImagePickerController alloc] init];
            cameraController.sourceType = UIImagePickerControllerSourceTypeCamera;
            cameraController.delegate = self;
            cameraController.allowsEditing = YES;
            [self presentViewController:cameraController animated:YES completion:nil];
        }else {
            
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"没有找到您的摄像头" message:@"请您检查摄像头" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            
        }
        
    }];
    [alertVC addAction: camera];
    [alertVC addAction:cancel];
    [alertVC addAction:photo];
    //    [alertVC addAction:];
    
    [self presentViewController:alertVC animated:YES completion:nil];

    
    
    
    
}

- (void)setImagePickerController:(UIImagePickerControllerSourceType)source{
    /**1:初始化相册控制器*/
    self.pickImage = [[UIImagePickerController alloc] init];
    /**2:设置代理*/
    self.pickImage.delegate = self;
    /**3:图片来源*/
    self.pickImage.sourceType = source;
    /**对图片大小位置选取*/
    [self.pickImage setEditing:YES];
    self.pickImage.allowsEditing = YES;
    [self presentViewController:self.pickImage animated:YES completion:nil];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    /**选出已经选中的图片*/
    self.loginImageV.image = [info objectForKey:UIImagePickerControllerEditedImage];
    


    self.loginImageV.image = info[@"UIImagePickerControllerOriginalImage"];
    [self saveImg];
    /**模态推出*/
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
